package org.dreamfly.core.util;

import org.apache.log4j.Logger;
import org.dreamfly.core.bean.SzAdmin;
import org.dreamfly.core.bean.SzAuthorities;
import org.dreamfly.core.bean.SzUsers;
import org.dreamfly.core.bean.User;
import org.dreamfly.core.dao.AdminDAO;
import org.dreamfly.core.dao.UserDAO;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: Gin
 * Date: 2010-11-30
 * Time: 21:28:20
 * To change this template use File | Settings | File Templates.
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    private UserDAO userDAO;
    private String server;
    private static Logger LOG= Logger.getLogger(UserDetailsServiceImpl.class);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        if (username == null) {
            LOG.error("username is null");
        }
        SzUsers user = userDAO.findByName(server,username);
        //TOTO 判断用户存在，如果不存在，则抛出异常。
        if (user == null) {
            LOG.error(username + " is not exist", new UsernameNotFoundException(username + " is not exist"));
            return null;
        }

        Set<GrantedAuthority> authsList = new HashSet<GrantedAuthority> ();

            for (Object authority : user.getSzAuthoritieses()) {
                authsList.add(new GrantedAuthorityImpl(((SzAuthorities)authority).getAuthor()));
            }

        org.springframework.security.userdetails.User userdetail = new User(
                user.getUsername(), user.getPassword(), true, true, true, true, authsList
                .toArray(new GrantedAuthority[authsList.size()]),user.getId());

        return userdetail;
    }

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void setServer(String server) {
        this.server = server;
    }
}
